package br.urca.impl;

import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;

import br.urca.dao.SolicitacaoCarteirinhaDAO;
import br.urca.model.SolicitacaoCarteirinha;
import br.urca.util.ESituacaoCarteirinha;

@Transactional
public class JPASolicitacaoCarteirinhaDAO implements SolicitacaoCarteirinhaDAO {
	
	private EntityManager manager;
	
	public JPASolicitacaoCarteirinhaDAO() {
		this(null);
	}
	
	@Inject
	public JPASolicitacaoCarteirinhaDAO(EntityManager manager) {
		this.manager = manager;
	}

	@Override
	public List<SolicitacaoCarteirinha> getList(String matricula) {
		try {
			return this.manager
					.createQuery(
							"SELECT s FROM SolicitacaoCarteirinha s "
									+ "WHERE s.id.matricula = :matricula",
							SolicitacaoCarteirinha.class)
					.setParameter("matricula", matricula).getResultList();
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public void salvar(SolicitacaoCarteirinha solicitacao) {
		this.manager.merge(solicitacao);
	}
	
	@Override
	public List<SolicitacaoCarteirinha> getListPorSituacao(
			ESituacaoCarteirinha situacao) {
		try {
			return this.manager
					.createQuery(
							"SELECT s FROM SolicitacaoCarteirinha s "
									+ "WHERE s.situacao = :situacao",
							SolicitacaoCarteirinha.class)
					.setParameter("situacao", (short) situacao.getTipo())
					.getResultList();
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public SolicitacaoCarteirinha getSolicitacao(String matricula,
			short via) {
		try {
			return this.manager
					.createQuery(
							"SELECT s FROM SolicitacaoCarteirinha s "
									+ "WHERE s.id.matricula = :matricula "
									+ "AND s.id.via = :via",
							SolicitacaoCarteirinha.class)
					.setParameter("matricula", matricula)
					.setParameter("via", via).getSingleResult();
		} catch (Exception e) {
			return null;
		}
	}

}
